//
// Created by denglibin on 19-10-29.
//

/**
 *udp通信服务端
 **/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <ctype.h>
#include <strings.h>
#include <arpa/inet.h>
#include <string.h>

#define SERVER_PORT 8000

static int main_(){
    int sfd;
    char buf[1024], client_ip[128];
    socklen_t  addr_len;
    struct sockaddr_in server_addr, client_addr;
    int i, len;
    addr_len = sizeof(client_addr);

    sfd = socket(AF_INET, SOCK_DGRAM, 0);

    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(sfd, (struct sockaddr*) &server_addr, sizeof(server_addr));

    while (1){
        bzero(buf, sizeof(buf));
        printf("wait for receive:\n");
        // 接收客户端的数据和地址信息
       len = recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&client_addr, &addr_len);
       printf("client: %s:%d\n",
               inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, client_ip, sizeof(client_ip)),
               ntohs(client_addr.sin_port));
       printf("%s", buf);
       for(i = 0; i < len; i++){
           buf[i] = (char)toupper((int)buf[i]);
       }
       // 发送数据给客户端
       sendto(sfd, buf, len, 0, (struct sockaddr *)& client_addr, addr_len);
    }

    return 0;
}